﻿using MediatR;
using Process.API.Application.Command.Action.ProductionMaterial;
using Process.Domain;
using Process.ErrorCode;
using Process.Infrastructure.Implement;

namespace Process.API.Application.Handler.Action.ProductionMaterial
{
    public class DelProductionMaterialHandler : IRequestHandler<DelProductionMaterialCommand, APIResult<int>>
    {
        private readonly DatabaseContext db;

        public DelProductionMaterialHandler(DatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<int>> Handle(DelProductionMaterialCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            if (request.ProductionOrdersId == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "生产工单ID不能为空";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            if (request.MaterialCodes == null || request.MaterialCodes.Count == 0)
            {
                result.Code = APIEnum.Fail;
                result.Message = "未选择需要删除的物料记录";
                result.Data = 0;
                return await Task.FromResult(result);
            }

            // 批量逻辑删除：根据生产工单ID和物料编号集合
            var affected = await db.SqlSugar
                .Updateable<ProductionMaterialTable>()
                .SetColumns(x => new ProductionMaterialTable { IsDel = true })
                .Where(x => x.ProductionOrdersId == request.ProductionOrdersId && 
                           request.MaterialCodes.Contains(x.MaterialCode) && 
                           x.IsDel == false)
                .ExecuteCommandAsync();

            result.Code = APIEnum.Ok;
            result.Message = "物料清单批量删除成功";
            result.Data = affected;
            return await Task.FromResult(result);
        }
    }
}
